package app.auto.runner.base.action;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;


import com.aliang.auto.R;
import com.zhy.autolayout.utils.AutoUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import app.auto.runner.base.MapViewConf;
import app.auto.runner.base.RRes;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.ShareAlert;

//已结束:[textcolor/color.gray,background/drawable.button_shap01],接诊:[textcolor/#ffffff,background/drawable.button_shap01]
public class ViewInflater extends LayoutInflater {
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static void tagrate(View view, Context ctx) {
        tagrate(view, null, ctx);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static void tagrate(View view, String tag, Context ctx) {
        if (view instanceof AdapterView) {
            tagrateListView(view, tag, ctx);
        } else if (view instanceof TextView) {
            TextView tv = ((TextView) view);
            String text = tv.getText().toString();
            if (TextUtils.isEmpty(tag)) {
                if (tv.getTag() == null || tv.getTag().toString().equals("")) {
                    return;
                }

                tag = tv.getTag().toString().replaceAll(" ", "");

            }
            String[] value = tag.split("],");
            //已结束:[textcolor/color.gray,background/drawable.button_shap01]
            Map map = MapBuilder.build().add("gray", "#ffcccccc")
                    .add("red", "#FF0000")
                    .add("green", "#3CB963")
                    .add("blue", "#3CB963")
                    .add("white", "#ffffff")
                    .add("transparent", "#FFFFFFFF")
                    .get();

            for (String v : value) {
                if (v.split(":")[0].equals(tv.getText())) {
                    String inner = v.split(":")[1].replace("[", "").replace("]", "");
                    String[] inners = inner.split(",");
                    for (String shxing : inners) {
                        String[] atts = shxing.split("/");
                        if (atts[0].equals("background")) {
                            if (atts[1].contains("#")) {
                                view.setBackgroundColor(Color.parseColor(atts[1]));

                            } else if (atts[1].contains("color.")) {
                                String somecolor = atts[1].replace("color.", "");
                                somecolor = somecolor.toLowerCase();
                                String color = (String) map.get(somecolor);
                                if (color != null) {
                                    view.setBackgroundColor(Color.parseColor(color));
                                }
                            } else if (atts[1].contains("drawable.")) {
                                RRes.initR(ctx);
                                int xmlvalue = RRes.get("R." + atts[1]).getAndroidValue();
                                view.setBackgroundResource(xmlvalue);

                            } else if (atts[1].contains("null")) {
                                view.setBackground(null);
                            }


                        } else if (atts[0].toLowerCase().equals("textcolor")) {
                            if (atts[1].contains("#")) {
                                tv.setTextColor(Color.parseColor(atts[1]));

                            } else if (atts[1].contains("color.")) {
                                String somecolor = atts[1].replace("color.", "");
                                somecolor = somecolor.toLowerCase();
                                String color = (String) map.get(somecolor);
                                if (color != null) {
                                    ((TextView) view).setTextColor(Color.parseColor(color));
                                }
                            }


                        } else if (atts[0].toLowerCase().equals("textsize")) {
                            atts[1] = atts[1].replace("px", "").replace("dip", "").replace("dp", "").replace("sp", "");
                            tv.setTextSize(Float.parseFloat(atts[1]));
                            AutoUtils.auto(tv);
                        }

                    }
                }
            }
        } else if (view instanceof ListView) {

        }
    }

    Context newContext;
    private boolean scale;

    public static final String packageName = "app.auto.runner.base.ui.";
    public static final Map<String, String> uiNames = new TreeMap<String, String>();

    static {
        uiNames.put("WebView", "android.webkit.");
        uiNames.put("CircleImageView", "android.support.v4.widget.");
        uiNames.put("ImageView", app.auto.runner.base.widget.ImageView.class.getPackage().getName() + ".");
//        uiNames.put("RoundImageView", RoundImageView.class.getPackage().getName() + ".");
        uiNames.put("WheelView", "top.smartsport.www.wheelview.");


//        uiNames.put("IjkPlayerView", "com.dl7.player.media.");
    }

    Set<String> layoutlog = new TreeSet<String>();

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException {

        View view = super.onCreateView(parent, name, attrs);
        if (parent != null && parent.getTag() != null) {
            if (!layoutlog.contains(parent.toString())) {
                layoutlog.add(parent.toString());
                parent.setOnClickListener(new ClickAction());
                fakeDataAdapterView(attrs, parent);
            }

        }
        return view;
    }


    public ViewInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
        this.newContext = newContext;
        this.scale = true;
        // TODO Auto-generated constructor stub

    }

    public static ViewInflater from(Context newContext) {
        return new ViewInflater(newContext);
    }

    public ViewInflater(Context newContext) {
        this(newContext, true);

    }

    public ViewInflater(Context newContext, boolean scale) {
        this(LayoutInflater.from(newContext), newContext);
        this.scale = scale;

    }

    @Override
    public LayoutInflater cloneInContext(Context arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public static ViewInflater fromAty(Context ctx) {
        return new ViewInflater(ctx, true);
    }

    public static ViewInflater fromAty(Context ctx, boolean scale) {
        return new ViewInflater(ctx, scale);
    }

    public String getValueString(String name, Object value) {
        name = name.toLowerCase();
        String res = "";
        if (value.toString().contains("@")) {
            res = RRes.getAttrValue_itsname().get(Integer.parseInt(value.toString().substring(1)));
            if (res == null) {
                return "";
            } else {
                if (name.contains("id")) {
                    res = "+" + res;
                }
                return res = "@" + res;
            }
        }
        return value.toString();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        // TODO Auto-generated method stub
        View view = null;
        try {
            MapBuilder.newInstance();
            MapBuilder.hold().add("name", name);
            for (int i = 0; i < attrs.getAttributeCount(); i++) {
                String aname = attrs.getAttributeName(i);
                String avalue = attrs.getAttributeValue(i);
//                attrs.getAttributeNameResource(i)
                MapBuilder.hold().add(aname, getValueString(aname, avalue));
//                if(aname.equals("id")){
//                    view.setTag(R.id.namedid,getValueString(aname, avalue));
//                }
            }
//            ShareAlert.shareAlert((Activity) newContext, MapBuilder.hold().get().toString());
            if (uiNames.containsKey(name)) {
                try {
                    view = (View) Class.forName(uiNames.get(name) + name)
                            .getConstructor(Context.class, AttributeSet.class)
                            .newInstance(newContext, attrs);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (name.equals("View") || name.contains(".")) {
                view = super.onCreateView(name, attrs);
            } else {
                view = super.createView(name, "android.widget.", attrs);
            }

            attributeset_from_view.put(view, attrs);
            if (view.getTag() != null) {
                if (view instanceof AdapterView) {
                    ((AdapterView) view).setOnItemClickListener(new ItemClickAction());
                } else {
                    view.setOnClickListener(new ClickAction());
                }
            }

            AutoUtils.autoSize(view);
            addTagAction(attrs, view);
            fakeDataAdapterView(attrs, view);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;

    }

    public View cloneView(View view) {
        try {
            return view.getClass().getConstructor(Context.class, AttributeSet.class).newInstance(newContext, getAttributeSet_From_View().get(view));
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;


    }

    public Map<View, AttributeSet> getAttributeSet_From_View() {
        return attributeset_from_view;
    }

    Map<View, AttributeSet> attributeset_from_view = new HashMap<View, AttributeSet>();

    private void addTagAction(AttributeSet attrs, View view) {
        try {

            final String tag = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "tag");
            if (tag != null && !tag.toLowerCase().contains("onclick")) {
                view.setOnClickListener(new View.OnClickListener() {

                    public Actions actions;

                    @Override
                    public void onClick(View v) {
                        if (actions == null) {
                            actions = Actions.withView(v).parse(tag);
                        }
                        actions.action();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Map<String, String> xml = new TreeMap<String, String>();

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void fakeDataAdapterView(AttributeSet attrs, View view) {
        try {
            if (view instanceof AdapterView) {
                String tag = attrs.getAttributeValue("http://schemas.android.com/apk/res/android", "tag");

                tagrateListView(view, tag, newContext);
            } else {
                ViewInflater.tagrate(view, newContext);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void tagrateListView(View view, String tag, Context newContext) {
        if (TextUtils.isEmpty(tag)) {
            tag = (String) view.getTag();
        }
        if (tag != null) {
            List list = new ArrayList();
            tag = tag.replaceAll(" ", "");
            if (tag.contains("fake:")) {
                int fake = tag.indexOf("fake:");
                fake += 5;
                int fakeend = -1;
                if (tag.contains(";")) {
                    fakeend = tag.indexOf(";", fake);

                } else {
                    fakeend = tag.length();
                }
                String content = tag.substring(fake, fakeend);
                content = content.replaceAll(" ", "");
                content = content.replaceAll("\\[\\[", "[").replaceAll("\\]\\]", "]");
                String[] contentAry = content.replaceAll("\\],", "]").split("\\]");
                for (String s : contentAry) {
                    if (s.equals("")) {
                        continue;
                    }
                    List alist = new ArrayList();
                    s = s.replaceAll("\\[", "");
                    String[] dataary = s.split(",");
                    for (String d : dataary) {
                        alist.add(d);
                    }
                    list.add(alist);
                }

            }
            int layoutid;
            if (tag.contains("layout:")) {
                int layout = tag.indexOf("layout:");
                layout += 7;
                int layoutend = -1;

                if (tag.substring(layout).contains(";")) {
                    layoutend = tag.indexOf(";", layout);

                } else {
                    layoutend = tag.length();
                }
                String content = tag.substring(layout, layoutend);
                content = content.replaceAll(" ", "");
                layoutid = RRes.get("R.layout." + content).getAndroidValue();
            } else {
                layoutid = R.layout.auto_string_item;
            }
            MapViewConf.with(newContext).conf(MapViewConf.with(newContext).source(layoutid)).source(list, view).toView();

        }
    }
}
